﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Traceability.App.DTO;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Company
{
    public class AddressQueryCommandHandler : IRequestHandler<AddressQueryCommand, APIResult<List<AddressDto>>>
    {
        private readonly IBaseRepository<T_CompanyAddress> addressRepository;

        public AddressQueryCommandHandler(IBaseRepository<T_CompanyAddress> addressRepository)
        {
            this.addressRepository = addressRepository;
        }

        public Task<APIResult<List<AddressDto>>> Handle(AddressQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<AddressDto>> result = new APIResult<List<AddressDto>>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            result.Data = GetAddress(0, request);
            return Task.FromResult(result);
        }

        private List<AddressDto> GetAddress(int pid, AddressQueryCommand request) 
        {
            var list = addressRepository.GetAll().AsNoTracking().Where(x => x.ParentId == pid);
            List<AddressDto> dtos = new List<AddressDto>();
            foreach (var item in list)
            {
                AddressDto dto = new AddressDto() 
                {
                    Value=item.ID,
                    Label=item.AddressName,
                    Children = GetAddress(item.ID,request)
                };
                dtos.Add(dto);
            }
            return dtos;
        }
    }
}
